<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {ArrowLeft, Plus} from '@element-plus/icons-vue'
import axios from 'axios'
import http from "@/request/Http.js";
import {useRoute, useRouter} from "vue-router";

// 路由相关
const router = useRouter();
const route = useRoute();

// 表单数据
const goodsForm = reactive({
  name: '',
  price: '',
  addressId: '',
  categoryId: '',
  detail: '',
  status: 1,
  images: [] // 存储图片URL和排序
})

// 地址列表
const addressList = ref([]);

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  price: [
    {required: true, message: '请输入商品价格', trigger: 'blur'},
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '价格格式错误（最多两位小数）',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (parseFloat(value) < 0.01) {
          callback(new Error('价格必须大于0'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  addressId: [
    {required: true, message: '请选择发货地址', trigger: 'change'}
  ],
  categoryId: [
    {required: true, message: '请选择商品分类', trigger: 'change'}
  ],
  detail: [
    {required: true, message: '请输入商品详情', trigger: 'blur'},
    {min: 10, message: '商品详情不能少于10个字符', trigger: 'blur'}
  ],
  images: [
    {required: true, message: '请至少上传一张商品图片', trigger: 'change'}
  ]
})

// 表单引用和文件列表
const goodsFormRef = ref()
const fileList = ref([])
const categoryList = ref([])
const isEditMode = ref(false)
const isLoading = ref(false) // 加载状态管理

// 验证用户登录状态（仅验证是否登录，不解析userId）
const checkLoginStatus = async () => {
  try {
    const token = sessionStorage.getItem('token')
    if (!token) return false

    // 调用用户信息接口验证登录状态
    const response = await http.get('/user/getUserInfo', {
      headers: {token}
    })
    return response.code === 200
  } catch (error) {
    console.error('验证登录状态失败:', error)
    return false
  }
}

// 获取分类列表
const getCategoryList = async () => {
  isLoading.value = true
  try {
    const response = await http.get('/classify/getAllCategories')
    if (response.code === 200) {
      categoryList.value = response.data || []
    } else {
      ElMessage.error('获取分类列表失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('网络错误，获取分类列表失败')
  } finally {
    isLoading.value = false
  }
}

// 获取地址列表（通过后端自动关联当前登录用户）
const getAddressList = async () => {
  isLoading.value = true
  try {
    // 直接调用/my接口，无需传递userId，由后端自动获取当前登录用户
    const response = await http.get('/address/my');
    console.log('获取地址列表响应:', response)
    if (response.code === 200) {
      addressList.value = response.data || []
      // 如果没有地址，提示用户添加
      if (addressList.value.length === 0) {
        ElMessageBox.confirm(
            '您还没有添加收货地址，是否现在去添加？',
            '提示',
            {
              confirmButtonText: '去添加',
              cancelButtonText: '稍后',
              type: 'info'
            }
        ).then(() => {
          router.push({path: '/userHome/Layout', query: {page: 'address'}});
        }).catch(() => {
        })
      }
    } else if (response.msg === '请先登录') {
      // 后端明确提示未登录时，引导登录
      ElMessage.warning('请先登录');
      setTimeout(() => {
        router.push('/login')
      }, 3000)
    } else {
      ElMessage.error('获取地址列表失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error("获取地址列表失败：", error)
    ElMessage.error("获取地址列表失败，请重试")
  } finally {
    isLoading.value = false
  }
};

// 获取商品详情（用于编辑回显）
const getGoodDetail = async (id) => {
  if (!id) return
  isLoading.value = true
  try {
    const response = await http.get(`/product/getGoodForEdit/${id}`);
    if (response.code === 200) {
      const good = response.data || {};

      // 回显基本信息
      goodsForm.name = good.name || '';
      goodsForm.price = good.price || '';
      goodsForm.addressId = good.addressId || '';
      goodsForm.categoryId = good.categoryId || '';
      goodsForm.detail = good.description || '';
      goodsForm.status = good.status ?? 1;

      // 回显图片
      if (good.images && good.images.length) {
        // 按排序号排序
        const sortedImages = [...good.images].sort((a, b) => (a.sort || 0) - (b.sort || 0));
        goodsForm.images = sortedImages.map(img => ({
          imageUrl: img.imageUrl || '',
          sort: img.sort || 0
        }));

        // 同步到文件列表（用于预览）
        fileList.value = sortedImages.map(img => ({
          url: img.imageUrl || '',
          uid: img.id || Date.now() + Math.random(),
          name: `image-${img.sort || 0}`
        }));
      }
    } else {
      ElMessage.error('获取商品信息失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取商品详情失败：', error);
    ElMessage.error('获取商品信息失败，请重试')
  } finally {
    isLoading.value = false
  }
};

// 处理文件变化
const handleFileChange = async (file, fileList) => {
  // 验证文件大小
  if (file.size > 500 * 1024) {
    ElMessage.error('文件大小不能超过500KB')
    // 移除超出大小的文件
    const index = fileList.findIndex(item => item.uid === file.uid)
    if (index !== -1) {
      fileList.splice(index, 1)
    }
    return
  }

  // 验证文件类型
  const acceptTypes = ['image/jpeg', 'image/png']
  if (!acceptTypes.includes(file.raw.type)) {
    ElMessage.error('仅支持jpg、png格式图片')
    const index = fileList.findIndex(item => item.uid === file.uid)
    if (index !== -1) {
      fileList.splice(index, 1)
    }
    return
  }

  if (file.raw) {
    const formData = new FormData()
    formData.append('file', file.raw)
    isLoading.value = true

    try {
      const response = await http.post('/file/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      console.log('图片上传响应:', response)
      let imageUrl = ''
      if (typeof response === 'string') {
        imageUrl = response
      }

      if (!imageUrl) {
        ElMessage.error('获取图片URL失败: ' + (response.data?.msg || '未知错误'))
        return
      }

      // 保存图片URL
      goodsForm.images.push({
        imageUrl: imageUrl,
        sort: goodsForm.images.length + 1
      })

      ElMessage.success('图片上传成功')

    } catch (error) {
      console.error('图片上传失败:', error)
      ElMessage.error('图片上传失败，请重试')
    } finally {
      isLoading.value = false
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 预览图片
const handlePreview = (file) => {
  if (!file.url && !file.thumbnailUrl) return
  ElMessageBox.alert(
      `<img src="${file.url || file.thumbnailUrl}" style="max-width:100%;max-height:300px"/>`,
      '图片预览',
      {
        dangerouslyUseHTMLString: true,
        customClass: 'image-preview-box'
      }
  )
}

// 移除图片
const handleRemove = async (file) => {
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index !== -1) {
    // 从列表中移除
    fileList.value.splice(index, 1)
    goodsForm.images.splice(index, 1)

    // 重新排序
    goodsForm.images.forEach((img, i) => {
      img.sort = i + 1
    })

    // 如果是已上传的图片，调用删除接口
    if (file.url) {
      try {
        await axios.delete('/file/delete', {
          params: {url: file.url}
        })
      } catch (err) {
        console.error('删除图片失败:', err)
        ElMessage.warning('图片删除失败，可能需要手动清理')
      }
    }
  }
}

// 提交表单（支持新增和编辑）
const handleSubmit = async () => {
  // 验证表单
  try {
    await goodsFormRef.value.validate()
  } catch (error) {
    ElMessage.error('表单验证失败，请检查输入项')
    return
  }

  // 验证图片
  if (!goodsForm.images || goodsForm.images.length === 0) {
    ElMessage.error('请至少上传一张商品图片')
    return
  }

  // 验证登录状态
  const isLoggedIn = await checkLoginStatus()
  if (!isLoggedIn) {
    ElMessage.warning('请先登录');
    setTimeout(() => {
      router.push('/login')
    }, 1000)
    return
  }

  // 准备提交数据
  const submitData = {
    name: String(goodsForm.name || ''),
    price: Number(goodsForm.price) || 0,
    addressId: Number(goodsForm.addressId) || null,
    status: Number(goodsForm.status) || 1,
    categoryId: Number(goodsForm.categoryId) || null,
    description: String(goodsForm.detail || ''),
    images: goodsForm.images.map((img, index) => ({
      imageUrl: String(img.imageUrl || ''),
      sort: Number(img.sort) || (index + 1)
    }))
  }

  isLoading.value = true
  try {
    const goodId = route.query.id;
    let response;

    // 区分新增和编辑接口
    if (goodId) {
      response = await http.put(`/product/updateGood/${goodId}`, submitData, {
        headers: {'Content-Type': 'application/json'}
      });
    } else {
      response = await http.post('/product/addGood', submitData);
    }
    console.log('提交数据:', response)
    if (response.code === 200) {
      ElMessage.success(goodId ? '商品修改成功！' : '商品发布成功！')
      await router.push('/userHome/showGoodList')
    } else {
      ElMessage.error(response.data?.msg || (goodId ? '商品修改失败' : '商品发布失败'))
    }
  } catch (error) {
    console.error('表单处理失败:', error)
    ElMessage.error('提交失败，请检查网络或联系管理员')
  } finally {
    isLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (goodsFormRef.value) {
    goodsFormRef.value.resetFields()
  }
  fileList.value = []
  goodsForm.images = []
}

// 监听图片列表变化，更新排序
watch(goodsForm.images, (newVal) => {
  newVal.forEach((img, index) => {
    img.sort = index + 1
  })
}, {deep: true})

// 页面加载时初始化数据
onMounted(() => {
  getCategoryList()
  getAddressList()

  // 检查是否有商品ID参数（编辑模式）
  const goodId = route.query.id;
  if (goodId) {
    isEditMode.value = true;
    getGoodDetail(goodId);
  }
})
</script>

<template>
  <div class="publish-goods-page">
    <!-- 加载遮罩 -->
    <el-loading
        v-if="isLoading"
        text="加载中..."
        background="rgba(255, 255, 255, 0.8)"
    />

    <!-- 返回按钮 -->
    <el-button :disabled="isLoading" class="back-btn" @click="goBack">
      <el-icon>
        <ArrowLeft/>
      </el-icon>
      返回
    </el-button>

    <!-- 表单容器 -->
    <div class="form-container">
      <h2 class="page-title">
        {{ isEditMode ? '修改商品' : '发布商品' }}
      </h2>

      <el-form
          ref="goodsFormRef"
          :model="goodsForm"
          :rules="formRules"
          label-width="120px"
      >
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input
              v-model="goodsForm.name"
              class="form-input"
              placeholder="请输入商品名称"
              :disabled="isLoading"
          ></el-input>
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price">
          <el-input
              v-model="goodsForm.price"
              class="form-input"
              placeholder="请输入商品价格"
              min="0"
              step="0.01"
              type="number"
              :disabled="isLoading"
          >
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>

        <!-- 发货地址 -->
        <el-form-item label="发货地址" prop="addressId">
          <el-select
              v-model="goodsForm.addressId"
              placeholder="请选择发货地址"
              :disabled="isLoading || addressList.length === 0"
          >
            <el-option
                v-for="address in addressList"
                :key="address.id"
                :label="`${address.province}${address.city}${address.district}${address.detail}`"
                :value="address.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item label="商品图片" prop="images">
          <el-upload
              :auto-upload="false"
              :file-list="fileList"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleFileChange"
              :disabled="isLoading"
              action="#"
              class="upload-demo"
              list-type="picture-card"
          >
            <el-icon class="upload-icon">
              <Plus/>
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png格式，单张不超过500kb</div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 商品分类 -->
        <el-form-item label="商品分类" prop="categoryId">
          <el-select
              v-model="goodsForm.categoryId"
              class="form-select"
              placeholder="请选择商品分类"
              :disabled="isLoading || categoryList.length === 0"
          >
            <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 商品详情 -->
        <el-form-item label="商品详情" prop="detail">
          <el-input
              v-model="goodsForm.detail"
              :rows="8"
              placeholder="请输入商品详情描述"
              type="textarea"
              :disabled="isLoading"
          ></el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="form-actions">
          <el-button
              class="submit-btn"
              type="primary"
              @click="handleSubmit"
              :loading="isLoading"
          >
            {{ isEditMode ? '保存修改' : '立即发布' }}
          </el-button>
          <el-button
              class="reset-btn"
              @click="resetForm"
              :disabled="isLoading"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 页脚 -->
    <div class="footer">
      <p>© 2024 二手交易平台 版权所有</p>
    </div>
  </div>
</template>

<style scoped>
.publish-goods-page {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9fafb;
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

.back-btn {
  margin-bottom: 20px;
  background-color: #f0f2f5;
  color: #303133;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e5e6eb;
}

.form-container {
  background-color: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.form-input, .form-select {
  width: 100%;
  max-width: 600px;
}

.upload-demo {
  margin-top: 5px;
}

.upload-icon {
  font-size: 28px;
  color: #8c8c8c;
}

.form-actions {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
}

.submit-btn {
  margin-right: 15px;
  padding: 8px 25px;
}

.reset-btn {
  padding: 8px 25px;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
}

.footer {
  text-align: center;
  margin-top: 50px;
  padding: 20px 0;
  font-size: 14px;
  color: #909399;
  border-top: 1px solid #f0f0f0;
}

/* 图片预览样式 */
:deep(.image-preview-box) {
  max-width: 80%;
}
</style>